#include <iostream>
#include <memory>
#include <vector>

using std::cout;
using std::endl;
using std::shared_ptr;
using std::vector;

void test()
{
    shared_ptr<int> sp(new int(10));
    cout << "*sp = " << *sp << endl;
    cout << "sp.get() = " << sp.get() << endl;
    cout << "sp.use_count() = " << sp.use_count() << endl;

    cout << endl << endl;
    shared_ptr<int> sp2(sp);//ok,复制
    cout << "*sp = " << *sp << endl;
    cout << "*sp2 = " << *sp2 << endl;
    cout << "sp.get() = " << sp.get() << endl;
    cout << "sp2.get() = " << sp2.get() << endl;
    cout << "sp.use_count() = " << sp.use_count() << endl;
    cout << "sp2.use_count() = " << sp2.use_count() << endl;

    cout << endl;
    shared_ptr<int> sp3(new int(30));
    cout << "*sp3 = " << *sp3 << endl;
    cout << "sp3.get() = " << sp3.get() << endl;
    cout << "sp3.use_count() = " << sp3.use_count() << endl;

    cout << endl;
    sp3 = sp;//ok, 赋值
    cout << "*sp = " << *sp << endl;
    cout << "*sp2 = " << *sp2 << endl;
    cout << "*sp3 = " << *sp3 << endl;
    cout << "sp.get() = " << sp.get() << endl;
    cout << "sp2.get() = " << sp2.get() << endl;
    cout << "sp3.get() = " << sp3.get() << endl;
    cout << "sp.use_count() = " << sp.use_count() << endl;
    cout << "sp2.use_count() = " << sp2.use_count() << endl;
    cout << "sp3.use_count() = " << sp3.use_count() << endl;

    cout << endl << "移动语义" << endl;
    shared_ptr<int> sp4(std::move(sp));//移动构造函数
    cout << "*sp4 = " << *sp4 << endl;
    cout << "sp4.get() = " << sp4.get() << endl;
    cout << "sp4.use_count() = " << sp4.use_count() << endl;

    cout << endl;
    sp4 = std::move(sp3);//移动赋值函数
    cout << "*sp4 = " << *sp4 << endl;
    cout << "sp4.get() = " << sp4.get() << endl;
    cout << "sp4.use_count() = " << sp4.use_count() << endl;

    cout << endl << "作为容器元素" << endl;
    vector<shared_ptr<int>> vec;
    /* vec.push_back(shared_ptr<int>(new int(1000))); */
    /* cout << "=== " <<  *vec[0] << endl; */
    //因为shared_ptr具备移动语义以及值语义，所以作为容器元素
    //的时候，既可以传递左值，也可以传递右值
    vec.push_back(sp4);//将sp4拷贝到vector
    vec.push_back(std::move(sp4));
    cout << "=== " <<  *vec[0] << endl;
    cout << "2222" << endl;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

